package com.bct.jxc.view;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.bct.jxc.common.CommonFactory;
import com.bct.jxc.common.StringUtil;
import com.bct.jxc.model.Customer;
import com.bct.jxc.model.Inport;
import com.bct.jxc.model.InportInfo;
import com.bct.jxc.model.Item;
import com.bct.jxc.model.Outport;
import com.bct.jxc.model.Product;
import com.bct.jxc.model.ProductInfo;
import com.bct.jxc.model.Provider;
import com.bct.jxc.model.Saleback;
import com.bct.jxc.model.SalebackInfo;
import com.bct.jxc.server.CustomerServer;
import com.bct.jxc.server.InportServer;
import com.bct.jxc.server.OutportServer;
import com.bct.jxc.server.ProductServer;
import com.bct.jxc.server.ProviderServer;
import com.bct.jxc.server.SalebackServer;

import javax.swing.JComboBox;
import java.awt.Component;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.ImageIcon;

public class SalebackInternalFrame extends JInternalFrame implements ActionListener{
	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	private MyTableModel tableModel;// 自定义表格模板，为了适配数据
	private JTable table;// 表格一定要放在JScrollPane，这样数据多的时候可以出现滚动条
	private JTextField idTf;
	private JTextField conTf;
	private JTextField timeTf;
	private JTextField handTf;
	private JTextField numberTf;
	private JTextField priceTf;
	private JTextField comTf;
	private JTextField operTf;
	JComboBox comboBox_1;//结算方式
	JComboBox comboBox;//供应商名称
	private ProductServer productServer;
	Item providerItem;
	private SalebackServer salebackServer;
	CustomerServer customerServer;
	private float price;//商品单价
	private String productId;//商品编号
	private String customerName = null;//商品名称

	/**
	 * Create the frame.
	 */
	public SalebackInternalFrame() {
		super("销售退货", true, true, true, true);
		setBounds(0, 0, 724, 384);

		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);

		JPanel panel_1 = new JPanel();

		JLabel lblNewLabel = new JLabel("退货单号：");
		lblNewLabel.setFont(new Font("楷体", Font.BOLD, 15));
		lblNewLabel.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/info.png")));

		idTf = new JTextField();
		idTf.setEditable(false);
		idTf.setColumns(20);

		JLabel lblNewLabel_1 = new JLabel("客户：");
		lblNewLabel_1.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/batch.png")));
		lblNewLabel_1.setFont(new Font("楷体", Font.BOLD, 15));

		comboBox = new JComboBox();
		comboBox.setMaximumRowCount(20);
		comboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				selectProviderAction();
				
			}
		});

		JLabel lblNewLabel_2 = new JLabel("联系人：");
		lblNewLabel_2.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/customer_query.png")));
		lblNewLabel_2.setFont(new Font("楷体", Font.BOLD, 15));
		lblNewLabel_2.setHorizontalAlignment(SwingConstants.TRAILING);

		conTf = new JTextField();
		conTf.setEditable(false);
		conTf.setColumns(15);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1
				.createSequentialGroup().addContainerGap().addComponent(lblNewLabel)
				.addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(idTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(ComponentPlacement.UNRELATED).addComponent(lblNewLabel_1)
				.addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
						GroupLayout.PREFERRED_SIZE)
				.addGap(18).addComponent(lblNewLabel_2).addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(conTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addContainerGap(364, Short.MAX_VALUE)));
		gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1
				.createParallelGroup(Alignment.BASELINE)
				.addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
				.addComponent(idTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addComponent(lblNewLabel_1)
				.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
						GroupLayout.PREFERRED_SIZE)
				.addComponent(lblNewLabel_2).addComponent(conTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
						GroupLayout.PREFERRED_SIZE)));
		panel_1.setLayout(gl_panel_1);

		JPanel panel_2 = new JPanel();

		JPanel panel_3 = new JPanel();
		// 创建表格的列（标题栏文字）
		String[] columNames = { "商品ID", "商品全称", "商品简称", "商品产地", "商品规格", "商品包装", "商品批号", "批准文号", "商品价格", "商品备注",
				"供应商全称" };
		// 实例化模板
		tableModel = new MyTableModel<ProductInfo>(columNames, ProductInfo.class);
		// 创建表格面板
		table = new JTable(tableModel);
		//表格行改变时监听
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				ListSelectionModel model = (ListSelectionModel) e.getSource();
				int index = model.getMaxSelectionIndex();
				//对index进行验证
				if(index == - 1) {
					return;
				}
				price = (float) table.getValueAt(index, 8);//商品价格
				productId = (String) table.getValueAt(index, 0);//商品编号
				//productName = (String) table.getValueAt(index, 1);//商品名称
				System.out.println(table.getValueAt(index, 0)+" "+price);
			}
		});
		table.setFont(new Font("宋体", Font.PLAIN, 12));
		// 设置表格大小
		table.setPreferredScrollableViewportSize(
				new Dimension(screenSize.width * 2 / 3 - 60, screenSize.height * 2 / 3));
		// 视图高度填充
		table.setFillsViewportHeight(true);
		table.setAutoCreateRowSorter(true);
		// 将表格放到滑动面板中
		JScrollPane scrollPane = new JScrollPane(table);
		panel_3.add(scrollPane);
		
		JPanel panel_4 = new JPanel();
		
		JPanel panel_5 = new JPanel();
		
		JPanel panel_6 = new JPanel();
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
				.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
				.addComponent(panel_4, GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
				.addComponent(panel_5, GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel_6, GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE)
					.addContainerGap())
				.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
					.addGap(2)
					.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
					.addGap(29)
					.addComponent(panel_6, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		
		JButton inportBtn = new JButton("退货");
		inportBtn.addActionListener(this);
		inportBtn.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/login.png")));
		inportBtn.setFont(new Font("楷体", Font.BOLD, 16));
		panel_6.add(inportBtn);
		
		JButton cancelBtn = new JButton("确认");
		cancelBtn.addActionListener(this);
		cancelBtn.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/queren.png")));
		cancelBtn.setFont(new Font("楷体", Font.BOLD, 16));
		panel_6.add(cancelBtn);
		
		JLabel lblNewLabel_8 = new JLabel("验收结论：");
		lblNewLabel_8.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/number.png")));
		lblNewLabel_8.setFont(new Font("楷体", Font.BOLD, 15));
		panel_5.add(lblNewLabel_8);
		
		comTf = new JTextField();
		panel_5.add(comTf);
		comTf.setColumns(20);
		
		JLabel lblNewLabel_9 = new JLabel("操作人员：");
		lblNewLabel_9.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/power_set.png")));
		lblNewLabel_9.setFont(new Font("楷体", Font.BOLD, 15));
		panel_5.add(lblNewLabel_9);
		
		operTf = new JTextField();
		operTf.setEditable(false);
		panel_5.add(operTf);
		operTf.setColumns(20);
		
		JLabel lblNewLabel_6 = new JLabel("商品数量：");
		lblNewLabel_6.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/bunber.png")));
		lblNewLabel_6.setFont(new Font("楷体", Font.BOLD, 15));
		panel_4.add(lblNewLabel_6);
		
		numberTf = new JTextField();
		panel_4.add(numberTf);
		numberTf.setColumns(20);
		
		JLabel lblNewLabel_7 = new JLabel("合计金额：");
		lblNewLabel_7.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/price.png")));
		lblNewLabel_7.setFont(new Font("楷体", Font.BOLD, 15));
		panel_4.add(lblNewLabel_7);
		
		priceTf = new JTextField();
		priceTf.setEditable(false);
		panel_4.add(priceTf);
		priceTf.setColumns(20);

		JLabel lblNewLabel_3 = new JLabel("结算方式：");
		lblNewLabel_3.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/price_roll.png")));
		lblNewLabel_3.setFont(new Font("楷体", Font.BOLD, 15));

		comboBox_1 = new JComboBox();
		comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "现金", "银联刷卡", "转账" }));
		panel_2.add(comboBox_1);

		JLabel lblNewLabel_4 = new JLabel("退货时间：");
		lblNewLabel_4.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/time.png")));
		lblNewLabel_4.setFont(new Font("楷体", Font.BOLD, 15));

		timeTf = new JTextField();
		timeTf.setEditable(false);
		timeTf.setColumns(20);

		JLabel lblNewLabel_5 = new JLabel("经手人：");
		lblNewLabel_5.setIcon(new ImageIcon(InportInternalFrame.class.getResource("/com/bct/jxc/images/customer.png")));
		lblNewLabel_5.setFont(new Font("楷体", Font.BOLD, 15));

		handTf = new JTextField();
		handTf.setColumns(20);
		GroupLayout gl_panel_2 = new GroupLayout(panel_2);
		gl_panel_2.setHorizontalGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_2
				.createSequentialGroup().addContainerGap().addComponent(lblNewLabel_3).addGap(8)
				.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
						GroupLayout.PREFERRED_SIZE)
				.addGap(18).addComponent(lblNewLabel_4).addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(timeTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addGap(12).addComponent(lblNewLabel_5).addPreferredGap(ComponentPlacement.UNRELATED)
				.addComponent(handTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addContainerGap(117, Short.MAX_VALUE)));
		gl_panel_2.setVerticalGroup(
				gl_panel_2.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel_2
						.createSequentialGroup().addContainerGap(GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)
						.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
								.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_3)
								.addComponent(handTf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_5).addComponent(timeTf, GroupLayout.PREFERRED_SIZE,
										GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_4))
						.addContainerGap()));
		panel_2.setLayout(gl_panel_2);
		panel.setLayout(gl_panel);

		productServer = CommonFactory.getProductServer();
		customerServer = CommonFactory.getCustomerService();
		salebackServer = CommonFactory.getsSalebackServer();
		initProviderComboBox();
		if (LoginFrame.getLoginUser() != null) {
			operTf.setText(LoginFrame.getLoginUser().getUsername());
		}
	}
	
	/**
	 * 初始化客户下拉选择框
	 */
	public void initProviderComboBox() {
		// 获取数据库中的数据
		List<Customer> list = customerServer.findCustomers(null);
		// 设置下来列表框中数据模型
		Vector<Item> items = new Vector<>();
		// 清空下拉列表框中的内容，免的重复
		comboBox.removeAllItems();
		// 迭代处理数据
		for (int i = 0; i < list.size(); i++) {
			Item it = new Item();
			it.setId(list.get(i).getId());
			it.setName(list.get(i).getCustomerName());
			it.setConstacts(list.get(i).getContracts());//联系人
			if (items.contains(it)) {// 如果集合中包含该元素，就不在添加
				continue;
			}
			items.add(it);
			comboBox.addItem(it);
		}
		
	}
	/**
	 * 下拉列表框点击事件(客户))
	 */
	private void selectProviderAction() {
		if (!(comboBox.getSelectedItem() instanceof Item)) {
			return;
		}
		providerItem = (Item) comboBox.getSelectedItem();
		System.out.println(providerItem.getId() + "," + providerItem.getName());
		//更新联系人
		conTf.setText(providerItem.getConstacts());
		customerName = providerItem.getName();
		//更新表格
//		ProductInfo pInfo = new ProductInfo();
//		pInfo.setProviderId(providerItem.getId());
		updateAllDate(null);
	}
	/**
	 * 更新数据
	 * @param product
	 */
	private void updateAllDate(ProductInfo product) {
		//查询数据库
		List<ProductInfo> products = productServer.findProducts(product);
		if(products != null) {
			Vector<ProductInfo> list = new Vector<ProductInfo>();
			for (ProductInfo c : products) {
				list.add(c);
			}
			//更新数据
			tableModel.updateData(list);
			//默认第一个价格
			products.get(0).getPrice();
		}
	}
	/**
	 * 点击事件
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		String target = e.getActionCommand();
		//InportInfo info = new InportInfo();
		SalebackInfo info = new SalebackInfo();
		info.setCustomerName(customerName);
		List<SalebackInfo> list = salebackServer.findAll(info);//根据商品查询销售表中是否有该商品
		//生成退货时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//合计金额
		float prices = 0;
		switch (target) {
		case "退货":
			
			boolean flag = checkNull();
			if(flag) {
				Date time = null;//处理日期
				try {
					time = sdf.parse(timeTf.getText().trim());
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
				//处理价格
				prices = Float.parseFloat(priceTf.getText().trim());
				
				//封装数据
				Saleback inport = new Saleback(idTf.getText().trim(), Integer.parseInt(numberTf.getText().trim()), 
						prices, comTf.getText().trim(), 
						((Item)(comboBox.getSelectedItem())).getId(), time, 
						operTf.getText().trim(), handTf.getText().trim(), 
						comboBox_1.getSelectedItem().toString(), productId);
				//退货入库
				boolean isFlag = salebackServer.add(inport);
				if(isFlag) {
					JOptionPane.showMessageDialog(null, "退货信息添加成功！","提示",JOptionPane.INFORMATION_MESSAGE);
					setNull();
					
				}else {
					JOptionPane.showConfirmDialog(null, "退货信息添加失败！","警告",JOptionPane.WARNING_MESSAGE);
				}
			}
			break;
		case "确认":
			if(list == null) {
				JOptionPane.showMessageDialog(null, "销售单中没有该商品", "警告", JOptionPane.WARNING_MESSAGE);
				return;
			}
			if(StringUtil.isEmpty(numberTf.getText().trim())) {
				JOptionPane.showMessageDialog(null, "商品数量不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
				return;
			}
			int num = Integer.parseInt(numberTf.getText().trim());
			int i = 0;
			while(i < list.size()) {
				if(num <= list.get(i).getAmount()) {
					break;
				}
				if(num > list.get(i).getAmount() && i == list.size() - 1) {
					JOptionPane.showMessageDialog(null, "商品数量不能大于入销售表中的商品的数量！", "警告", JOptionPane.WARNING_MESSAGE);
					return;
				}
				i++;
			}
			//生成退货单号
			String id = salebackServer.getId();
			idTf.setText(id);
			String date = sdf.format(new Date());
			timeTf.setText(date);
			//商品合计价格
			prices = price * num;
			priceTf.setText(prices+"");
			break;
		default:
			break;
		}
		
	}
	/**
	 * 清空数据
	 */
	private void setNull() {
		idTf.setText("");
		comboBox.setSelectedIndex(0);
		comboBox_1.setSelectedIndex(0);
		timeTf.setText("");
		handTf.setText("");
		numberTf.setText("");
		priceTf.setText("");
		comTf.setText("");
	}

	/**
	 * 非空验证
	 */
	public boolean checkNull() {
		boolean flag = true;
		if(StringUtil.isEmpty(idTf.getText().trim())) {
			JOptionPane.showMessageDialog(null, "退货单号能为空！","警告",JOptionPane.WARNING_MESSAGE);
			flag = false;
		}
		if(StringUtil.isEmpty(timeTf.getText().trim())) {
			JOptionPane.showMessageDialog(null, "退货时间能为空！","警告",JOptionPane.WARNING_MESSAGE);
			flag = false;
		}
		if(StringUtil.isEmpty(handTf.getText().trim())) {
			JOptionPane.showMessageDialog(null, "经手人不能为空！","警告",JOptionPane.WARNING_MESSAGE);
			flag = false;
		}
		if(StringUtil.isEmpty(numberTf.getText().trim())) {
			JOptionPane.showMessageDialog(null, "商品数量不能为空！","警告",JOptionPane.WARNING_MESSAGE);
			flag = false;
		}
		if(StringUtil.isEmpty(comTf.getText().trim())) {
			JOptionPane.showMessageDialog(null, "验收结论人不能为空！","警告",JOptionPane.WARNING_MESSAGE);
			flag = false;
		}
		return flag;
	}
	
}
